package com.whq.thrift.api.gateway.filter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.whq.common.http.HttpClientUtil;
import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.constants.CommonErrorCodeConstants;
import com.whq.thrift.api.common.thriftclient.ThriftApiJsonClientHelper;
import com.whq.thrift.api.common.thriftclient.model.ResponseModuleList;

public class GatewayIceClientHelper extends ThriftApiJsonClientHelper {
	private static final Logger LOGGER = LoggerFactory.getLogger(GatewayIceClientHelper.class);
	private static final Logger LOGGER_QUARTZ = LoggerFactory.getLogger(CommonConfigConstants.LOGGER_KEY_QUARTZ);
	
	// <url, UrlMethodMapping>
	private static final Map<String, UrlMethodMapping> MAP_URL_METHOD = new HashMap<String, UrlMethodMapping>(0);
	
	private String thriftGatewayInstancesUrl = "";
	
	private String urlMappingUrl = "";
	
	public void initialize() {
		super.initialize();
		
		doRefreshGatewayThriftInstances();
		doRefreshUrlMethodMapping();
	}
	
	public void doRefreshGatewayThriftInstances() {
		LOGGER_QUARTZ.info("begin refresh gateway thrift service client instances from url[" + thriftGatewayInstancesUrl + "]");
		
		Map<String, String> paramsMap = new HashMap<String, String>(0);
		String responseStr = HttpClientUtil.fetchStrByGetMethod(thriftGatewayInstancesUrl, paramsMap, false, 3000, 3000);
		
		LOGGER_QUARTZ.info("request url[" + thriftGatewayInstancesUrl +"], params[" + paramsMap + "], response[" + responseStr + "]");
		ResponseModuleList responseModuleList = null;
		try {
			responseModuleList = JSON.parseObject(responseStr, ResponseModuleList.class);
		} catch (Exception e) {
			LOGGER.error("parse response[" + responseStr + "] to ResponseModuleList exception: ", e);
		}
		
		if ( (responseModuleList != null)
				&& (responseModuleList.getReturnCode() == CommonErrorCodeConstants.ERR_CODE_SUCCESS)
				&& (responseModuleList.getData() != null)
				){
			refreshServiceInstance(responseModuleList.getData());	
		}
		
		LOGGER_QUARTZ.info("end refresh gateway thrift service client instances from url[" + thriftGatewayInstancesUrl + "]");
	}
	
	public void doRefreshUrlMethodMapping() {
		LOGGER_QUARTZ.info("begin refresh url method mapping from url[" + urlMappingUrl + "]");
		
		Map<String, String> paramsMap = new HashMap<String, String>(0);
		String responseStr = HttpClientUtil.fetchStrByGetMethod(urlMappingUrl, paramsMap, false, 3000, 3000);
		
		LOGGER_QUARTZ.info("request url[" + urlMappingUrl +"], params[" + paramsMap + "], response[" + responseStr + "]");
		
		ResponseUrlMappingInfo responseUrlMappingList = null;
		try {
			responseUrlMappingList = JSON.parseObject(responseStr, ResponseUrlMappingInfo.class);
		} catch (Exception e) {
			LOGGER.error("parse response[" + responseStr + "] to ResponseUrlMappingInfo exception: ", e);
		}
		
		if ( (responseUrlMappingList != null) 
				&& (responseUrlMappingList.getReturnCode() == CommonErrorCodeConstants.ERR_CODE_SUCCESS) 
				&& (responseUrlMappingList.getData() != null) ) {
			// 先把所有的改成待清理状态
			for (Entry<String, UrlMethodMapping> entry: MAP_URL_METHOD.entrySet()) {
				UrlMethodMapping value = entry.getValue();
				if (value != null) {
					value.setNeedRemove(true);
				}
			}
			
			Map<String, String> urlMethodMap = new HashMap<String, String>(0);
			for (Iterator<UrlMethodMapping> iterator = responseUrlMappingList.getData().iterator(); iterator.hasNext();) {
				UrlMethodMapping oneRecord = (UrlMethodMapping) iterator.next();
				if (oneRecord != null) {
					urlMethodMap.put(oneRecord.getUrl(), oneRecord.getMapParamMethod());
					
					oneRecord.setNeedRemove(false);
					MAP_URL_METHOD.put(oneRecord.getUrl(), oneRecord);
				}
			}
			
			// 清理需要清理的数据
			for (Iterator<Entry<String, UrlMethodMapping>> iterator = MAP_URL_METHOD.entrySet().iterator(); iterator.hasNext();) {
				Entry<String, UrlMethodMapping> entry = (Entry<String, UrlMethodMapping>) iterator.next();
				UrlMethodMapping value = entry.getValue();
				if ( (value != null) && (value.isNeedRemove())) {
					iterator.remove();
				}
			}
			
		}
		
		LOGGER_QUARTZ.info("end refresh url method mapping from url[" + urlMappingUrl + "]");
	}
	
	/**
	 * 根据url获取映射的method参数
	 * @param url
	 * @return
	 */
	public String getMapParamMethodByUrl(String url) {
		UrlMethodMapping urlMethodMapping = MAP_URL_METHOD.get(url);
		if (urlMethodMapping == null) {
			return null;
		}
		return urlMethodMapping.getMapParamMethod();
	}

	public String getThriftGatewayInstancesUrl() {
		return thriftGatewayInstancesUrl;
	}

	public void setThriftGatewayInstancesUrl(String thriftGatewayInstancesUrl) {
		this.thriftGatewayInstancesUrl = thriftGatewayInstancesUrl;
	}

	public String getUrlMappingUrl() {
		return urlMappingUrl;
	}

	public void setUrlMappingUrl(String urlMappingUrl) {
		this.urlMappingUrl = urlMappingUrl;
	}
	
}
